package com.rdxer.core.jpaex;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.SneakyThrows;

import javax.persistence.AttributeConverter;
import java.util.HashMap;
import java.util.Map;

public class MapToJsonConverter implements AttributeConverter<Map<String,Object>,String> {

    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();

    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(Map<String,Object> o) {
        return objectMapper.writeValueAsString(o);
    }

    @SneakyThrows
    @Override
    public Map<String,Object> convertToEntityAttribute(String s) {
        return objectMapper.readValue(s, typeFactory.constructMapType(HashMap.class, String.class,Object.class));
    }
}